//
//  HKGoPoliceViewController.m
//  AQBPolice
//
//  Created by apple on 2017/7/6.
//  Copyright © 2017年 eight. All rights reserved.
//

#import "HKGoPoliceViewController.h"
#import "HKDisposePoliceViewController.h"

@interface HKGoPoliceViewController ()

/**
 地址
 */
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;

/**
 poi
 */
@property (weak, nonatomic) IBOutlet UILabel *poiLabel;

/**
 距离
 */
@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;

@end

@implementation HKGoPoliceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(renewUI) name:@"hasPoliceNotification" object:nil];
    
    
    
}

- (void)renewUI {

    //获取案件详情
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    double distance = [userDefaults doubleForKey:@"distance"];
    NSString *address = [userDefaults objectForKey:@"address"];
    if ([address containsString:@"自治区"]) {
        NSString *shortAddress = [address componentsSeparatedByString:@"自治区"][1];
        address = shortAddress;
    }
    //更新UI
    self.addressLabel.text = [NSString stringWithFormat:@"%@", [userDefaults objectForKey:@"poi"]];
    self.poiLabel.text = address;
    
    if (distance > 1000) {
        double currDistance = distance / 1000;
        self.distanceLabel.text = [NSString stringWithFormat:@"%.2lf公里", currDistance];
    }else {
        self.distanceLabel.text = [NSString stringWithFormat:@"%.2lf米", distance];
    }
}

- (IBAction)goPoliceButtonClicked:(id)sender {
    //展示处理警情界面
    UIViewController *disposeVC = [[UIStoryboard storyboardWithName:@"Dispose" bundle:nil] instantiateInitialViewController];
    [self presentViewController:disposeVC animated:YES completion:nil];
    
    //发送通知，处理警情界面更新UI
    [[NSNotificationCenter defaultCenter] postNotificationName:@"disposePoliceNotification" object:nil];
    
    //发送通知，安全宝界面结束倒计时的Timer，取消听警
    [[NSNotificationCenter defaultCenter] postNotificationName:@"didGoPoliceNotification" object:nil];
    
    //接警(网络)
    [self acceptAlarmWithAlarmId:alarmNum andPoliceId:policeNumber];
}

- (IBAction)canNotGoPoliceButtonClicked:(id)sender {
    HKLog(@"alarmId是%@", alarmNum);
    //拒绝接警(网络)
    [self refuseAlarmWithAlarmId:alarmNum andPoliceId:policeNumber];
    //发送通知，通知SecureVC界面收起接警详情界面
    NSNotification *notification = [NSNotification notificationWithName:@"CanNotGoPoliceNotification" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}


#pragma mark - 网络请求
/**
 拒绝接警
 @param alarmId 案件号
 @param policeId 警号
 */
- (void)refuseAlarmWithAlarmId:(NSString *)alarmId andPoliceId:(NSString *)policeId {
    NSURLSession *session = [NSURLSession sharedSession];
    NSString *urlString = [baseURL stringByAppendingString:@"mobile/police/refuseAlarm/"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    request.HTTPMethod = @"POST";
    NSString *alarmStr = [NSString stringWithFormat:@"alarmId=%@", alarmId];//参数1：案件编号
    NSString *policeStr = [NSString stringWithFormat:@"&policeId=%@", policeId];//参数2：警号
    
    request.HTTPBody = [[alarmStr stringByAppendingString:policeStr] dataUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
        if (data == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"网络错误" toView:self.view];
            });
        }else {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            if ([dict[@"meta"] isEqual: @"success"]) {//拒绝接警成功
                HKLog(@"拒绝接警成功");
                
            }else {//发送实时位置失败
                HKLog(@"拒绝接警失败");
            }
        }
    }];
    [task resume];
}


/**
 同意接警
 @param alarmId 案件号
 @param policeId 警号
 */
- (void)acceptAlarmWithAlarmId:(NSString *)alarmId andPoliceId:(NSString *)policeId {
    NSURLSession *session = [NSURLSession sharedSession];
    NSString *urlString = [baseURL stringByAppendingString:@"mobile/police/acceptAlarm/"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    request.HTTPMethod = @"POST";
    NSString *alarmStr = [NSString stringWithFormat:@"alarmId=%@", alarmId];//参数1：案件编号
    NSString *policeStr = [NSString stringWithFormat:@"&policeId=%@", policeId];//参数2：警号
    
    request.HTTPBody = [[alarmStr stringByAppendingString:policeStr] dataUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
        if (data == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"网络错误" toView:self.view];
            });
        }else {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            if ([dict[@"meta"] isEqual: @"success"]) {//接警成功
                NSString *civilianTel = dict[@"civilianTel"];
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:civilianTel forKey:@"civilianTel"];
                
                HKLog(@"接警成功");
            }else {//发送实时位置失败
                HKLog(@"接警失败");
            }
        }
    }];
    [task resume];
}

/**
 修改出警的状态
 @param state 1为停警，2为出警
 */
- (void)modifyPoliceState:(NSString *)state {
    NSURLSession *session = [NSURLSession sharedSession];
    NSString *urlString = [baseURL stringByAppendingString:@"mobile/police/modifyPoliceState/"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    request.HTTPMethod = @"POST";
    NSString *phoneStr = [NSString stringWithFormat:@"state=%@", state];//1表示停警，2表示出警
    NSString *msgStr = [NSString stringWithFormat:@"&policeId=%@", policeNumber];
    request.HTTPBody=[[phoneStr stringByAppendingString:msgStr] dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionDataTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
        if (error) {//如果出现网络问题直接返回
            return;
        }
        if (data == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"网络错误" toView:self.view];
            });
        }else {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            if ([dict[@"meta"] isEqual: @"success"]) {//成功
                if([state isEqualToString:@"2"]) {
                    HKLog(@"修改状态为出警");
                }else {
                    HKLog(@"修改状态为停警");
                }
            }else {//失败
                if([state isEqualToString:@"2"]) {
                    HKLog(@"修改状态为停警");
                }else {
                    HKLog(@"修改状态为出警");
                }
            }
        }
    }];
    [task resume];
}


- (void)dealloc {
    //移除监听
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"CanNotGoPoliceNotification" object:nil];
}

@end
